﻿/**
 * ImageUploader
 *
 * ImageUploader class uploads an image to a server or downloads an image from a server.
 * The class also encodes a BitmapData to a JPEG file, and uploads the image to a server.
 *
 * ImageUploader is part of the sample application for the presentation on Flash ActionScript Cafe's 2nd conference.
 * 
 *
 * @author: Han Sanghun (http://hangunsworld.com, hanguns@gmail.com)
 * @created: 2008 05 16
 * @last modified: 2008 05 24
 */

package conf{
	
	//import asfiles.encoding.JPEGEncoder;
	
	import asfiles.encoding.JPEGEncoder;
	
	import flash.display.*;
	import flash.events.*;
	import flash.net.*;
	import flash.utils.ByteArray;
	import flash.utils.setTimeout;
	
	
	public class ImageUploader{
		
		private var _root:*;
		
		
		
		// 업로드용 파일레퍼런스
		private var fr:FileReference;
		private var fr_filter:FileFilter;
		private var fr_filter2:FileFilter;
		private var fr_ur:URLRequest;
		private var fr_uv:URLVariables;
		
		// 이미지 저장
		private var save_ul:URLLoader;
		private var save_ur:URLRequest;
		private var save_uv:URLVariables;
		private var save_urHeader:URLRequestHeader;
		
		// 다운로드용 파일레퍼런스
//		private var down_fr:FileReference;
//		private var down_ur:URLRequest;
		
		
		// 인코딩위한 변수
		private const BOUNDARY:String = "---------------------------7d76d1b56035e";
		private var FormData:String;
		private var FormData2:String;
		private var encoder:JPEGEncoder;
		private var ba:ByteArray;
		private var dataArray:ByteArray;
		
		
		/**
		 * Constructor function.
		 */
		public function ImageUploader(mc:*){
			
			_root = mc;
			
/*			
			// 업로드 용
			fr = new FileReference();
			fr.addEventListener(Event.SELECT, fileSelectListener);
			fr.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, fileUploadListener);
			fr.addEventListener(IOErrorEvent.IO_ERROR, errorListener);
			fr.addEventListener(ProgressEvent.PROGRESS, progressListener);
			
			fr_filter = new FileFilter("Images", "*.jpg;*.gif;*.png");
			//fr_filter2 = new FileFilter("All", "*.*");
			
			fr_ur = new URLRequest();
			fr_ur.url = cfv.SERVER_PATH + cfv.FILE_PATH;
			
			fr_uv = new URLVariables();
			fr_uv.newName = "upload_test.jpg";
			*/
			
			
			// 인코딩 및 저장 용
			//encoder = new JPEGEncoder(80);
			
			encoder = new JPEGEncoder(50);
			
//			encoder.addEventListener(ProgressEvent.PROGRESS, onEncodingProgress);
//			encoder.addEventListener(Event.COMPLETE, onEncodingComplete);
			
			dataArray = new ByteArray();
			
			save_ul = new URLLoader();
			save_ul.addEventListener(Event.COMPLETE, saveCompleteListener);
			save_ul.addEventListener(IOErrorEvent.IO_ERROR, errorListener);
			save_ul.addEventListener(ProgressEvent.PROGRESS, progressListener);
			save_ur = new URLRequest();
			save_ur.url = cfv.SERVER_PATH + cfv.FILE_PATH;
			
			save_uv = new URLVariables();
			save_urHeader = new URLRequestHeader("Accept","image/jpeg, image/jpg");
			
			
			
			// 다운로드 용
//			down_fr = new FileReference();
//			down_fr.addEventListener(Event.COMPLETE, downCompleteListener);
//			down_fr.addEventListener(ProgressEvent.PROGRESS, progressListener);
//			down_fr.addEventListener(IOErrorEvent.IO_ERROR, errorListener);
//			down_fr.addEventListener(Event.CANCEL, downCompleteListener);
//			
//			down_ur = new URLRequest();
			
		}// end constructor function
		
		
		
		/**
		 * 파일 브라우저 창 열기
		 */
		public function browse():void{
			
			fr.browse([fr_filter]);
			//fr.browse([fr_filter, fr_filter2]);
			
		}// end browse
		
		
		
		/**
		 * 파일 선택하면, 업로드하기
		 */
		private function fileSelectListener(e:Event):void{
			
			// 업로드
			fr_ur.data = fr_uv;
			fr.upload(fr_ur);
			
		}// end fileSelectListener
		
		/**
		 * 업로드 완료하면, 리턴된 경로의 이미지 로드하기
		 */
		private function fileUploadListener(e:DataEvent):void{
			
			_root.loadImage(e.data);
			
		}// end fileUploadListener
		
		/**
		 * 업로드 IO에러 발생 이벤트리스너
		 */
		private function errorListener(e:IOErrorEvent):void{
			
			_root.showMessage("An I/O error has been occured.", true);
			
		}// end fileErrorListener
		
		/**
		 * 프로그레스 이벤트리스너
		 */
		private function progressListener(e:ProgressEvent):void{
			
			_root.showMessage("Progesss " + uint(e.bytesLoaded / e.bytesTotal * 100) + "%", false, uint(e.bytesLoaded / e.bytesTotal * 100));
			
		}// end progressListener
		
		
		
		
		/**
		 * JPEG 이미지 인코드하기
		 *
		 * @param bd JPEG로 인코드할 비트맵데이터
		 */
		public var thumbSeq:int;
		public function enocdeJPEG(bd:BitmapData, thumbSeq:int, dv:String='', makedFileName:String=null):String{
			
			ba = encoder.encode(bd);
			
			//return;
			//var filename:String = "save_test.jpg";
			var filename:String;
			if(makedFileName == null) {
				filename = dv+"_"+thumbSeq.toString()+ "_" + cfv.now.fullYear.toString()+ cfv.now.month.toString() + cfv.now.date.toString()+ "_" + int(Math.random()*100)+".jpg";	
			} else {
				filename = makedFileName;
			}
			 
			
			// 헤더 만들기
			FormData  =  "--" + BOUNDARY + '\r\nContent-Disposition: form-data; name="Filedata"; filename="'+ filename + '"\r\nContent-Type: application/octet-stream\r\n\r\n';
			FormData2 = "\r\n";
			FormData2 += "--" + BOUNDARY + '\r\nContent-Disposition: form-data; name="userid"; \r\n\r\n' + cfv.USERID + '\r\n';
			
			//FormData2 += "--" + BOUNDARY + '\r\nContent-Disposition: form-data; name="dv"; \r\n\r\n' + dv + '\r\n';
			
			FormData2 += "--" + BOUNDARY + '--';
			
			
			// 바이트 어레이 합치기
			dataArray.length = 0;
			dataArray.writeMultiByte(FormData,"ascii");
			var iLen:int = ba.length;
			for(var k:uint=0; k<iLen; k++){
				dataArray.writeByte(ba[k]);
			}	
			dataArray.writeMultiByte(FormData2,"ascii");
			 
			
			// 서버로 전송하기
			
			save_ur.requestHeaders.push(save_urHeader);
			save_ur.data = dataArray;
			save_ur.method = URLRequestMethod.POST;
			save_ur.contentType = "multipart/form-data; boundary=" + BOUNDARY;
			
			save_ul.load(save_ur);
			
			return filename;
		}// end encodeJPEG
		
		/**
		 * 이미지 저장 완료하면, 리턴된 경로의 이미지 다운로드하기
		 */
		private function saveCompleteListener(e:Event):void{
			_root.showMessage("saveCompleteListener.");
			setTimeout(_root.hideMessage, 1000)
//			down_ur.url = _root.SERVER_PATH + save_ul.data;
//			down_fr.download(down_ur);
			
		}// end saveCompleteListener
		
		/**
		 * 이미지 저장 IO에러 발생 이벤트리스너
		 */
		private function saveErrorListener(e:IOErrorEvent):void{
			
			_root.showMessage("The image saving process failed\rbecause of an IOError.", true);
			
		}// end saveErrorListener
		
		
		
		
		/**
		 * 이미지 다운로드 완료하면, 메세지 팝업 제거
		 */
		private function downCompleteListener(e:Event):void{
			
			_root.hideMessage();
			
		}// end downCompleteListener
		
	}// end class
}// end package